const Parse = require('parse/node');
const StudentDeviceObj = Parse.Object.extend("v5_emooc_student_device");
const UsersObj = Parse.Object.extend('v5_user');
const ParseHelper = require('../helpers/parse');
const axios =require('axios');
const getData = (resp) => {
    return resp.data
};

//查询用户绑定的实验箱
async function getUserByOwner(username) {
    const query = new Parse.Query(StudentDeviceObj);
    query.equalTo("username", username);
    query.notEqualTo("isDeleted", true);
    query.select('emoocId', 'username');
    const result = await query.first({ useMasterKey: true });
    if(result){
        const jsonResult = ParseHelper.toJSON(result);
        jsonResult.hardware_id = jsonResult.emoocId;
        delete jsonResult.emoocId;
        jsonResult.user = jsonResult.username;
        delete jsonResult.username;
        return jsonResult;
    }else{
        return result;
    }

}

function result(ok, message) {
    return {ok, message}
}
//绑定硬木设备
async function bindDevice(emoocId,username){
    const query = new Parse.Query(StudentDeviceObj);
    const user=await getUserByOwner(username);
    query.equalTo("emoocId", emoocId);
    query.notEqualTo("isDeleted", true);
    const queryDevice=await query.first({ useMasterKey: true });
    if(user){
        return  result(false, "绑定失败：用户已关联其它实验箱，请联系指导教师");
    }
    else if(queryDevice){
        return  result(false, "绑定失败：实验箱已关联其它账号，请联系指导教师");
    }
    else {
        const device = new StudentDeviceObj();
        device.set("emoocId",emoocId);
        device.set("username",username);
        await device.save(null,{ useMasterKey: true });
        return  result(true, "绑定成功");
    }
}

async function wxBindDevice(username,emoocId){
    const device = new StudentDeviceObj();
    device.set("emoocId",emoocId);
    device.set("username",username);
    await  device.save(null,{ useMasterKey: true });
    return  result(true, "绑定成功");
}

// 解绑硬木设备
async function unBindDevice(bindId) {
    const query = new Parse.Query(StudentDeviceObj);
    const bindObj =await query.get(bindId,{ useMasterKey: true });
    bindObj.set('isDeleted',true);
    return bindObj.save(null,{ useMasterKey: true })
}



async function unbind_device(deviceId){
    const query = new Parse.Query(StudentDeviceObj);
    query.equalTo("emoocId", deviceId);
    query.notEqualTo("isDeleted", true);
    const queryDevice=await query.first({ useMasterKey: true });
    if(queryDevice){
        queryDevice.set('isDeleted',true);
        return queryDevice.save({ useMasterKey: true })
    }
    else {
        return null
    }

}

//获取支撑系统emooc数据
async function getEmoocTimeRecords(sStartDate,sEndDate) {
    const records = axios.post('http://emooc.koudaishiyan.com/emooc/time_record_sometime',
        {begin:sStartDate, end:sEndDate},).then(getData).catch(e=>{return []});
    return records;
}

//查询实验箱绑定关系
async function getDevicesUser(emoocIds) {
    const query = new Parse.Query(StudentDeviceObj);
    query.containedIn("emoocId", emoocIds);
    query.notEqualTo("isDeleted", true);
    query.select('emoocId', 'username');
    const result = await query.find({ useMasterKey: true }).then(ParseHelper.toJSONList);
    return result;
}

//绑定硬木设备
// async function bindDevice(username,emoocId){
//     const query = new Parse.Query(StudentDeviceObj);
//     const user=await getUserByOwner(username);
//     query.equalTo("emoocId", emoocId);
//     query.notEqualTo("isDeleted", true);
//     const queryDevice=await query.first({ useMasterKey: true });
//     if(user){
//         throw "绑定失败：用户已关联其它实验箱，请联系指导教师";
//     }
//     else if(queryDevice){
//         throw "绑定失败：实验箱已关联其它账号，请联系指导教师";
//     }
//     else {
//         const device = new StudentDeviceObj();
//         device.set("emoocId",emoocId);
//         device.set("username",username);
//         const reslut = await device.save(null,{ useMasterKey: true });
//         const jsonResult = ParseHelper.toJSON(reslut);
//         jsonResult.hardware_id = jsonResult.emoocId;
//         delete jsonResult.emoocId;
//     }
// }

// 通过emoocId查询绑定的那个学生信息
async function getEmoocIdStudent(emoocIds) {
    const query = new Parse.Query(StudentDeviceObj);
    query.notEqualTo('isDeleted',true);
    query.containedIn('emoocId',emoocIds);
    query.limit(9999);
    const studentDevices =await query.find({ useMasterKey: true }).then(ParseHelper.toJSONList);
    // 获取学生信息
    const usernames = studentDevices.map(device => device.username);
    const userQuery = new Parse.Query(UsersObj);
    userQuery.notEqualTo('isDeleted',true);
    userQuery.limit(9999);
    userQuery.containedIn('username',usernames);
    const studentInfo = await userQuery.find({ useMasterKey: true }).then(ParseHelper.toJSONList);
    // 把学生的姓名放入设备绑定的信息中
    return studentDevices.map(device => {
        studentInfo.forEach(student => {
            if(student.username === device.username){
                device.studentShowName = student.showName;
                device.studentUsername = student.username;
                device.studentNumber = student.studentNumber
            }
        });
        return device
    })
}

async function unBindDevices(deviceId){
    const query = new Parse.Query(StudentDeviceObj);
    query.notEqualTo('isDeleted',true);
    query.containedIn('deviceId',deviceId);
    return  query.find({ useMasterKey: true }).then(parseDevice=>{
       parseDevice.set('isDeleted',true);
       return parseDevice.save()
    });
}
async function getBindInfo(deviceId){
    const query = new Parse.Query(StudentDeviceObj);
    query.equalTo("emoocId", deviceId);
    query.notEqualTo("isDeleted", true);
    return await query.find({ useMasterKey: true }).then(ParseHelper.toJSONList);

}

module.exports={
    bindDevice,
    unBindDevice,
    unbind_device,
    unBindDevices,
    getBindInfo,
    wxBindDevice,
    getUserByOwner
};